package com.zp.game


import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.helloandroid.AppUtil
import com.helloandroid.app.model.AppCache
import com.helloandroid.ext.parseZhuanPanInfo
import com.helloandroid.ext.process
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.NetWorkUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class ZpViewModel: ViewModel() {

    fun getInfo(callback:(Boolean,ZhuanPanInfo?)->Unit){

        val info = AppCache.copyZpInfo()
        if (info != null){
            callback(true,info)
            return
        }

        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打开网络!")
            callback(false,null)
            return
        }

        viewModelScope.launch {
            val url = "game/zhuanpan/info?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseZhuanPanInfo)

            if(parseResult.err == 0){
                val zpInfo = parseResult.obj as ZhuanPanInfo
                AppCache.zpInfo = zpInfo
                callback(true,AppCache.copyZpInfo())
            }else{
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false,null)
            }
        }
    }

//    //
//    fun delayRun(delayMs:Long,action:()->Unit){
//        viewModelScope.launch {
//            delay(delayMs)
//            action.invoke()
//        }
//    }
}